package com.ants.project.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 发送文本邮件
 * 发送图片邮件
 * 发送附件邮件
 * Created by liushun on 2016/6/30.
 */
public class MailUtil {

    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

    public static Properties mailProp = new Properties();
    //主机 //账号 //密码
    public static String host = "", account = "", passowrd = "";
    //端口
    public static int port = 0;
    //调试
    public static boolean debug = false;
    static {
        Properties properties = new Properties();
        //读取resources下面的配置
        InputStream is = MyDBUtil.class.getResourceAsStream("/config.properties");
        try {
            properties.load(is);
            host = String.valueOf(properties.get("mail.host"));
            port = Integer.parseInt(properties.get("mail.port").toString());
            account = String.valueOf(properties.get("mail.account"));
            passowrd = String.valueOf(properties.get("mail.password"));
            debug = Boolean.valueOf(properties.get("mail.debug").toString());

            mailProp.setProperty("mail.host", host);
            mailProp.setProperty("mail.transport.protocol", String.valueOf(properties.get("mail.protocol")));
            mailProp.setProperty("mail.smtp.auth", String.valueOf(properties.get("mail.auth")));
            mailProp.setProperty("mail.debug", String.valueOf(properties.get("mail.debug")));
        } catch (IOException e) {
            logger.error("config.properties is no found !" + e.getMessage());
        }
    }

    enum EmailType {
        TextType, FileType, ImageType;
    }
    /**
     * 发送邮件
     *
     * @param fromTo    目标邮箱
     * @param title     邮件标题
     * @param content   文本内容
     * @param fileNames 附件数组
     * @param type      邮件类型 0、纯文本邮件 1、附件邮件 2、图片邮件 3、图片附件邮件
     */
    public static void sendMail(String fromTo, String title, String content, String[] fileNames, EmailType type) {
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(mailProp);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(debug);
        //2、通过session得到transport对象
        Transport ts = null;
        MimeMessage message = null;
        try {
            ts = session.getTransport();
            //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
            ts.connect(host, port, account, passowrd);
            //创建消息体
            if (type == EmailType.TextType) message = TxtMessage(fromTo, title, content, session);
            else if (type == EmailType.FileType) message = FileMessage(fromTo, title, content, fileNames, session);
            else if (type == EmailType.ImageType) message = ImageMessage(fromTo, title, content, fileNames, session);
            //5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 不带附件发送文件
     *
     * @param fromTo
     * @param title
     * @param content
     */
    public static void sendMail(String fromTo, String title, String content) {
        sendMail(fromTo, title, content, null, EmailType.TextType);
    }

    /**
     * 文本消息体
     *
     * @param fromTo  目标邮箱
     * @param title   标题
     * @param content 内容
     * @param session
     * @return
     */
    public static MimeMessage TxtMessage(String fromTo, String title, String content, Session session) {
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        try {
            message.setFrom(new InternetAddress(account));
            //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(fromTo));
            //邮件的标题
            message.setSubject(title);
            //邮件的文本内容
            message.setContent(content, "text/html;charset=UTF-8");
            //返回创建好的邮件对象
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 附件消息体
     *
     * @param fromTo    目标邮箱
     * @param title     标题
     * @param content   内容
     * @param fileNames 附件数组
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage FileMessage(String fromTo, String title, String content, String[] fileNames, Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        //设置邮件的基本信息
        //发件人
        message.setFrom(new InternetAddress(account));
        //收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(fromTo));
        //邮件标题
        message.setSubject(title);

        //创建邮件正文，为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");

        //创建容器描述数据关系
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(text);
        mp.setSubType("mixed");

        for (String fileName : fileNames) {
            //创建邮件附件
            MimeBodyPart attach = new MimeBodyPart();
            DataHandler dh = new DataHandler(new FileDataSource(fileName));
            attach.setDataHandler(dh);
            attach.setFileName(dh.getName());  //

            mp.addBodyPart(attach);
        }

        message.setContent(mp);
        message.saveChanges();
        //将创建的Email写入到E盘存储
        //   message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
        //返回生成的邮件
        return message;
    }

    /**
     * 附件消息体
     *
     * @param fromTo      目标邮箱
     * @param title       标题
     * @param content     内容
     * @param imagesNames 图片数组
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage ImageMessage(String fromTo, String title, String content, String[] imagesNames, Session session) throws Exception {
        //创建邮件
        MimeMessage message = new MimeMessage(session);
        // 设置邮件的基本信息
        //发件人
        message.setFrom(new InternetAddress(account));
        //收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(fromTo));
        //邮件标题
        message.setSubject(title);

        // 准备邮件数据
        // 准备邮件正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");

        // 描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.setSubType("related");
        for (String imagesName : imagesNames) {
            // 准备图片数据
            MimeBodyPart image = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(imagesName);
            DataHandler dh = new DataHandler(fileDataSource);
            image.setDataHandler(dh);
            image.setContentID(fileDataSource.getName());
            mm.addBodyPart(image);
        }
        message.setContent(mm);
        message.saveChanges();
        //将创建好的邮件写入到E盘以文件的形式进行保存
        //message.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
        //返回创建好的邮件
        return message;
    }
}
